/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
//var baseUrl='http://10.0.0.7:8220/utopia-web/app';
var baseUrl='http://www.jjstar.cc:8220/utopia-web/app';
(function($, owner) {
	/**
	 * 用户登录
	 **/
	owner.login = function(loginInfo, callback) {
		callback = callback || $.noop;
		loginInfo = loginInfo || {};
		loginInfo.account = loginInfo.account || '';
		loginInfo.password = loginInfo.password || '';
		if(loginInfo.account==''){
			return callback('手机号不能为空');
		}
		if(!owner.checkPhone(loginInfo.account)){
			return callback('手机号有误');
		}
		if (loginInfo.password.length < 6) {
			return callback('密码不能少于6位');
		}
		var waitLogin = plus.nativeUI.showWaiting();
		$.ajax(baseUrl + '/appLogin',{
			data:{
				tel:loginInfo.account,
				password:loginInfo.password,
			},
			dataType:'json',
			type:'post',
			success:function(data){
				waitLogin.close();
				callback(data.info)
				if(data.status=='ok'){
					//本地存储用户登录信息
					plus.storage.setItem("account",loginInfo.account);
					plus.storage.setItem("password",loginInfo.password);
					plus.storage.setItem("token",data.mapInfo.shopsUser.token);
					return owner.createState(data.mapInfo.shopsUser.userTel,data.mapInfo.shopsUser.token,callback);
				}else{
					
				}
			},
			error:function(xhr,type,errorThrown){
				waitLogin.close();
				callback('网络不给力，请检查网络或稍后再试');
			}
		});
	};

	owner.createState = function(tel,token,callback) {
		var state = owner.getState();
		state.account = tel;
		state.token = token;
		owner.setState(state);
		return callback();
	};

	/**
	 * 新用户注册
	 **/
	owner.reg = function(regInfo, callback) {
		callback = callback || $.noop;
		regInfo = regInfo || {};
		regInfo.account = regInfo.account || '';
		regInfo.password = regInfo.password || '';
		if (regInfo.account.length < 5) {
			return callback('用户名最短需要 5 个字符');
		}
		if (regInfo.password.length < 6) {
			return callback('密码最短需要 6 个字符');
		}
		if (!checkEmail(regInfo.email)) {
			return callback('邮箱地址不合法');
		}
		var users = JSON.parse(localStorage.getItem('$users') || '[]');
		users.push(regInfo);
		localStorage.setItem('$users', JSON.stringify(users));
		return callback();
	};

	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		var stateText = localStorage.getItem('$state') || "{}";
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};

	var checkEmail = function(email) {
		email = email || '';
		return (email.length > 3 && email.indexOf('@') > -1);
	};

	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(email, callback) {
		callback = callback || $.noop;
		if (!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};

	/**
	 * 获取应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		localStorage.setItem('$settings', JSON.stringify(settings));
	}

	/**
	 * 设置应用本地配置
	 **/
	owner.getSettings = function() {
			var settingsText = localStorage.getItem('$settings') || "{}";
			return JSON.parse(settingsText);
		}
		/**
		 * 获取本地是否安装客户端
		 **/
	owner.isInstalled = function(id) {
		if (id === 'qihoo' && mui.os.plus) {
			return true;
		}
		if (mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager)
			var packageName = {
				"qq": "com.tencent.mobileqq",
				"weixin": "com.tencent.mm",
				"sinaweibo": "com.sina.weibo"
			}
			try {
				return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
			} catch (e) {
			}
		} else {
			switch (id) {
				case "qq":
					var TencentOAuth = plus.ios.import("TencentOAuth");
					return TencentOAuth.iphoneQQInstalled();
				case "weixin":
					var WXApi = plus.ios.import("WXApi");
					return WXApi.isWXAppInstalled()
				case "sinaweibo":
					var SinaAPI = plus.ios.import("WeiboSDK");
					return SinaAPI.isWeiboAppInstalled()
				default:
					break;
			}
		}
	}
	// 获取支付通道
	owner.getChannels=function(){
		
		plus.payment.getChannels(function(channels){
			for(var i in channels){
				var channel=channels[i];
				if(channel.id=='qhpay'||channel.id=='qihoo'){	// 过滤掉不支持的支付通道：暂不支持360相关支付
					continue;
				}
				pays[channel.id]=channel;							
			}
		},function(e){
			plus.nativeUI.toast('获取支付通道失败：'+e.message);
		});
	}
	// 检测是否安装支付服务
	owner.checkServices=function(pc){
		if(!pc.serviceReady){
			var txt=null;
			switch(pc.id){
				case 'alipay':
				txt='检测到系统未安装“支付宝快捷支付服务”，无法完成支付操作，是否立即安装？';
				break;
				default:
				txt='系统未安装“'+pc.description+'”服务，无法完成支付，是否立即安装？';
				break;
			}
			plus.nativeUI.confirm(txt, function(e){
				if(e.index==0){
					pc.installService();
				}
			}, pc.description);
			return false;
		}else{
			return true;
		}
	}
	/***********************************/
	//阻止冒泡
	owner.stopPropagation=function(e) { 
		e = e || window.event; 
		if(e.stopPropagation) { //W3C阻止冒泡方法 
			e.stopPropagation(); 
		} else { 
			e.cancelBubble = true; //IE阻止冒泡方法 
		} 
	}
	owner.openViwe=function(url,id,extras){
		$.openWindow({
				url:url,
				id:id||url,
				styles:{
					"popGesture":'hide'
				},
				show:{
					aniShow: 'pop-in'
				},
				extras:extras,
				waiting:{
					autoShow:false
				}
		});
	}
	owner.openViwe2=function(url,id,extras){
		$.openWindow({
				url:url,
				id:id||url,
				styles:{
					"popGesture":'none'
				},
				show:{
					aniShow: 'pop-in'
				},
				extras:extras,
				waiting:{
					autoShow:false
				}
		});
	}
	owner.showLogin=function(){
		$.openWindow({
			url:'login.html',
			id:'login.html',
			styles:{
				"popGesture":'hide',
			},
			show:{
				aniShow:'pop-in'
			},
			waiting:{
				autoShow:false
			}
		});
	}
	//验证手机号
	owner.checkPhone= function(phone){ 
	     if(!(/^1[3|4|5|7|8][0-9]{9}$/.test(phone))){ 
	        return false; 
	    }else{
	    	return true;
	    }
	}
	//输入框不能输入汉字
	owner.checkCharacters= function(str){ 
	    var temp="" 
		for(var i=0;i<str.length;i++) 
		     if(str.charCodeAt(i)>0&&str.charCodeAt(i)<255) 
		        temp+=str.charAt(i) 
		return temp; 
	}
	owner.navTab=function(){
		$(".mui-bar-tab").on('tap','.mui-tab-item',function(){
			$.openWindow({
				url:this.getAttribute("data-href"),
				id:this.getAttribute("data-href"),
				styles:{
					popGesture:"none"
				},
				show:{
					aniShow:'none'
				},
				waiting:{
					autoShow:false
				}
			})
		})
	}
}(mui, window.app = {}));
